#include "Sokoban.h"

void  sokInit(Sokoban *pSok)
{
	pSok->x=7;
	pSok->y=8;
	pSok->etat=0;
}

/*void  sokInit(Sokoban *pSok,const Terrain *pTer)
{
	int x,y;
	for(y=0;y<getDimY(pTer);y++)
		for(x=0;x<getDimX(pTer);x++)
		{
			if(pTer->tab[y][x]=='$')
			{
				pSok->x=x;
				pSok->y=y;
				pSok->etat=0;
				
			}	
			
		}	
}*/	

/*Sokoban *sokRecupere(const Terrain *pTer)
{
	Sokoban sok;
	int x,y;
	for(y=0;y<getDimY(pTer);y++)
		for(x=0;x<getDimX(pTer);x++)
		{
			if(pTer->tab[y][x]=='$')
			{
				sok->x=x;
				sok->y=y;
				sok->etat=0;
				return sok;
				
			}	
			
		}	
}*/

void sokGauche(Sokoban *pSok, const Terrain *pTer, Caisse *pCai)
{
  int caiOk;
	if (terEstPositionSokoValide( pTer, pSok->x-1, pSok->y))
        {
	    caiOk=caiRecherche(pCai, pSok->x-1,pSok->y);
	    if(caiOk)
	      {
		caiOk=caiRecherche(pCai,pSok->x-2,pSok->y);
		if(caiOk==0)
		  {
		  caiGauche(pTer, pCai->x-2, pCai->y);
		  pSok->x--;
	       
		  }
	      }
	    else
	       pSok->x--;
	  }
}

void sokDroite(Sokoban *pSok, const Terrain *pTer, Caisse *pCai)
{
  int caiOk;
	if (terEstPositionSokoValide( pTer, pSok->x+1, pSok->y))
        {
	    caiOk=caiRecherche(pCai, pSok->x+1,pSok->y);
	    if(caiOk)
	      {
		caiOk=caiRecherche(pCai, pSok->x+1,pSok->y);
		if(caiOk==0)
		  {
		  caiDroite(pTer, pCai->x+2, pCai->y);
		  pSok->x++;
		  
		  }
	      }
	    else
	       pSok->x++;
	}
}

void sokHaut(Sokoban *pSok, const Terrain *pTer, Caisse *pCai)
{
  int caiOk;
	if (terEstPositionSokoValide( pTer, pSok->x, pSok->y-1))
	  {
	    caiOk=caiRecherche(pCai, pSok->x,pSok->y-1);
	    if(caiOk)
	      {
		caiOk=caiRecherche(pCai, pSok->x,pSok->y-2);
		if(caiOk==0)
		  {
		  caiHaut(pTer, pCai->x, pCai->y-2);
		  pSok->y--;
		  
		  }
	      }
	    else
	       pSok->y--;
	  }
 }

void sokBas(Sokoban *pSok, const Terrain *pTer, Caisse *pCai)
{
  int caiOk;
	if (terEstPositionSokoValide( pTer, pSok->x, pSok->y+1))
	  {
	    caiOk=caiRecherche(pCai, pSok->x,pSok->y+1);
	    if(caiOk)
	      {
		caiOk=caiRecherche(pCai, pSok->x,pSok->y+2);
		if(caiOk==0)
		  {
		    caiBas(pTer, pCai->x, pCai->y+2);
		    pSok->y++;
		  
		  }
	      }
	    else
	       pSok->y++;
	    
	  }
}

int sokGetX(const Sokoban *pSok)
{
	return pSok->x;
}

int sokGetY(const Sokoban *pSok)
{
	return pSok->y;
}
